package com.mms.utils;

import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by dan3652@sina.com on 2016-12-21 17:47.
 */
public class BaiduApi {
    private static String httpUrl = "http://apis.baidu.com/xiaogg/changetopinyin/topinyin";
    private static String httpArg = "type=json&traditional=0&accent=0&letter=0&only_chinese=0&str=";
    private static String apikey = "96c00eb0237706c0deb519a902448721";
//    String jsonResult = request(httpUrl, httpArg);

    /**
     * @param arg 参数
     * @return 返回结果
     */
    public static String requestPinYin(String arg) {
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
         httpUrl = httpUrl + "?" + httpArg + arg;

        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            // 填入apikey到HTTP header
            connection.setRequestProperty("apikey",  apikey);
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
            }
            reader.close();
            result = sbf.toString();
            JSONObject obj = (JSONObject) JSONObject.parse(result);
            result = obj.getString("pinyin").replaceAll("\\s*", "");;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
